﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using LitJson;
using System.Drawing;
using System.Drawing.Imaging;

namespace point2bmp
{
    public partial class main
    {
        static void ModPic2Point()
        {
            // 读取贴图
            Image img = null;
            try
            {
                img = Image.FromFile(basepath + moddir + "1-mod.png");
                img.Save(basepath + moddir + "1-mod-min.png", ImageFormat.Png);
            }
            catch (Exception)
            {
                Console.WriteLine("无法找到图片");
            }
            if (img == null)
            {
                return;
            }
            Bitmap bmp = new Bitmap(img);
            
            // 读取贴图信息，然后映射到cellmap中。
            for (int y = 0; y < cellcount; y ++) 
            {
                for (int x = 0; x < cellcount; x ++)
                { 
                    // 如果次方块内已经有值，那么算作已处理。
                    if (cellMap[x, y] != null)
                        continue;

                    // 读取一个方块内的像素值，如果像素值大于平均值，说明有数据。
                    double colorvalue = 0;
                    for (int j = 0; j < cellheight; j++)
                    {
                        for (int i = 0; i < cellwidth; i++)
                        {
                            var color = bmp.GetPixel(i+x*cellwidth, j+y*cellheight);
                            if (color.R > 128 && color.G < 128 && color.B < 128)
                                colorvalue += color.R * 65536 + color.G * 256 + color.B; 
                        }
                    }
                    // 如果方块内一般都有内容，说明有效。
                    if (colorvalue > 0.5 * cellwidth * cellheight * 0xFFFFFF)
                    {
                        if (cellMap[x, y] == null)
                        {
                            cellMap[x, y] = new PathNode() { WorldPos = null, Neighbours = new List<PathNode>(), Idx = x, Idy = y };
                        }
                    }
                }
            }
            DrawCellToPng("aftermode-");

            Pic2All("-mod");
        }
        static void Pic2All()
        {
            Pic2All("");
        }
        static void Pic2All(string tag)
        {

            // 阶段2开始
            // 计算邻居信息

            FindPathNodeFunc GetNeighbour = delegate(int x, int y)
            {
                if (x >= 0 && y >= 0 && x < cellcount && y < cellcount)
                    return cellMap[x, y];
                return null;
            };

            for (int y = 0; y < cellcount; y++)
            {
                for (int x = 0; x < cellcount; x++)
                {
                    if (cellMap[x, y] != null)
                    {
                        cellMap[x, y].Neighbours.Clear();
                        // 下右上左
                        {
                            var nbor = GetNeighbour(x, y + 1);
                            if (nbor != null)
                                cellMap[x, y].Neighbours.Add(nbor);
                        }
                        {
                            var nbor = GetNeighbour(x + 1, y);
                            if (nbor != null)
                                cellMap[x, y].Neighbours.Add(nbor);
                        }
                        {
                            var nbor = GetNeighbour(x, y - 1);
                            if (nbor != null)
                                cellMap[x, y].Neighbours.Add(nbor);
                        }
                        {
                            var nbor = GetNeighbour(x - 1, y);
                            if (nbor != null)
                                cellMap[x, y].Neighbours.Add(nbor);
                        }
                    }
                }
            }

            // 设置使用次数
            foreach (var it in cellMap)
            {
                if (it != null)
                {
                    it.TempUseCount = it.Neighbours.Count + 1;
                }
            }

            // 检索所有的点，直到都放入了close表。
            List<List<PathNode>> allpath = new List<List<PathNode>>();
            for (int y = 0; y < cellcount; y++)
            {
                for (int x = 0; x < cellcount; x++)
                {
                    var it = cellMap[x, y];
                    if (it != null)
                    {
                        if (it.TempUseCount <= 0)
                        {
                            continue;
                        }
                        List<PathNode> path = new List<PathNode>();

                        // 寻找一条路径。
                        do
                        {
                            path.Add(it);
                            it.TempUseCount--;  // 标记此点已经走过一次

                            // 遍历邻居
                            {
                                PathNode tmp = null;
                                foreach (var nbor in it.Neighbours)
                                {
                                    if (nbor == null)
                                        continue;
                                    if (nbor.TempUseCount <= 0)
                                        continue;
                                    if (path.Contains(nbor))
                                        continue;
                                    tmp = nbor;
                                    break;
                                }
                                // 因为邻居可用，所以标记此点又走过一次
                                if (tmp != null)
                                {
                                    it.TempUseCount--;
                                    tmp.TempUseCount--;
                                }

                                // 将邻居点作为当前路点，准备继续遍历
                                it = tmp;
                            }
                        } while (it != null);

                        if (path.Count > 0)
                            allpath.Add(path);
                    }
                }
            }

            Color[] allcolors = {Color.Blue, Color.Green,
                                Color.Yellow, Color.YellowGreen,
                                Color.Tomato, Color.Thistle,
                                Color.Silver, Color.Teal};

            // 将所有的路线绘制出来。      
            Image pathimg = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics gpath = Graphics.FromImage(pathimg);
            for (int i = 0; i < allpath.Count; i++)
            {
                var path = allpath[i];
                Pen pathpen = new Pen((allcolors[i % allcolors.Length]));
                foreach (var it in path)
                {
                    gpath.FillRectangle(pathpen.Brush, it.Idx * cellwidth, it.Idy * cellheight, cellwidth, cellheight);
                }
            }
            pathimg.Save(basepath + outdir + "allpath" + 0 + tag + ".png", ImageFormat.Png);

            // 将路点输出成json
            for (int i = 0; i < allpath.Count; i++)
            {
                var path = allpath[i];
                List<MyVector3> waypoints = new List<MyVector3>();
                foreach (var it in path)
                {
                    if (it.WorldPos == null)
                        continue;

                    waypoints.Add(it.WorldPos);
                }

                string jsonStr = JsonMapper.ToJson(waypoints);
                File.WriteAllText(basepath + outdir + "seq-waypoints" + i + tag + ".json", jsonStr);
            }

        }
    }
}
